package com.example.javabasic.thread.classtwo.workthread.demo1;

import java.util.Arrays;

//自定义队列
public class Channel {
    private static final int MAX = 100;
    private final Request[] requestQueue;
    //头
    private int head;
    //尾
    private int tail;
    //总数
    private int count;

    private final WorkerThread[] workerPool;


    public Channel(int workers) {
        this.requestQueue = new Request[MAX];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.workerPool = new WorkerThread[workers];
        this.init();
    }

    private void init() {
        //创建 指定个数的消费者,
        for (int i = 0; i < workerPool.length; i++) {
            workerPool[i] = new WorkerThread("worker" + i, this);
        }
    }


    public void startWorker() {
        Arrays.asList(workerPool).stream().forEach(WorkerThread::start);
    }

    //队列中放入
    public synchronized void put(Request request) {
        //当 count >  队列长度  说明满了
        while (count >= requestQueue.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {

            }
        }
        this.requestQueue[this.tail] = request;
        this.tail = this.tail+1 % requestQueue.length;
        this.count++;
        System.out.println(Thread.currentThread().getName()+"生产了"+ request.toString());
        this.notifyAll();
    }

    //队列中取出
    public synchronized Request take() {
        while (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = this.requestQueue[this.head];
        this.head = this.head+1 % requestQueue.length;
        this.count--;
        System.out.println("工人 "+Thread.currentThread().getName()+"消费了->"+ request.toString()+ "剩余:"+this.count);
        return request;
    }

}
